//
//  SCOneLoginTool.m
//  Shuaiche
//
//  Created by yujunyang on 2021/4/13.
//  Copyright © 2021 ShuaiChe. All rights reserved.
//

#import "SCOneLoginTool.h"
#import <Masonry/Masonry.h>
#import "MBProgressHUD+Add.h"
#import "SCLoginVC.h"
#import "SCNavigationController.h"
#import "AppDelegate.h"
#import "SCHttpManager.h"
#import <JPUSHService.h>
#import "Config.h"
#import "NSString+Helper.h"
#import "SCNetworkStatusConst.h"
#import "UIImage+Color.h"

@interface  SCOneLoginTool()<UIGestureRecognizerDelegate>
{
  void(^otherLogin_)(void);
}
@property (strong, nonatomic) OLAuthViewModel *viewModel;

@end


@implementation SCOneLoginTool

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.viewModel = [self authViewModel];
        [Config sharedConfig].isPresentedWhenSessionExpired = YES;
    }
    return self;
}

#pragma mark - Action
- (void)requestIsOneLogin:(BOOL)isPresented viewController:(UIViewController *)viewController otherLogin:(void (^)(void))otherLogin {
    otherLogin_ = otherLogin;
    if (!isPresented) {
        self.viewModel.pullAuthVCStyle = OLPullAuthVCStylePush;
    }else{
        self.viewModel.pullAuthVCStyle = OLPullAuthVCStyleModal;
    }
    self.isPresented = isPresented;
    self.viewController = viewController;
    if ([OneLogin isPreGettedTokenValidate]) {
        [OneLogin requestTokenWithViewController:_viewController viewModel:self.viewModel completion:^(NSDictionary * _Nullable result) {
            [self finishRequestingToken:result];

        }];
    }else{
        [OneLogin preGetTokenWithCompletion:^(NSDictionary * _Nonnull preResult) {
            NSLog(@"preGetTokenWithCompletion result: %@", preResult);
            if (preResult.count > 0 && preResult[@"status"] && 200 == [preResult[@"status"] integerValue]) {
                [OneLogin requestTokenWithViewController:self.viewController viewModel:self.viewModel completion:^(NSDictionary * _Nullable result) {
                    NSLog(@"requestTokenWithViewController result: %@", result);
                
                    [self finishRequestingToken:result];

                }];
            } else {    // 预取号失败
                otherLogin();
//                [GTProgressHUD showToastWithMessage:preResult[@"msg"]?:@"预取号失败"];
            }
        }];
    }
}

- (OLAuthViewModel *)authViewModel{

    OLAuthViewModel *viewModel = [OLAuthViewModel new];
    
    viewModel.backgroundColor = SC_Color_NavWhite;
   
    viewModel.naviBgColor = SC_Color_NavWhite;
    viewModel.naviTitle = [[NSAttributedString alloc] initWithString:@"登录"
                                                          attributes:@{NSForegroundColorAttributeName : UIColor.blackColor,
                                                                       NSFontAttributeName : SC_FONT_Bold(18)}];
//    viewModel.naviBackImage = [UIImage imageNamed:@"back_icon"];
  
    viewModel.naviHidden = YES;

    viewModel.appLogo = [UIImage imageNamed:@"icon_app_logo"];
    viewModel.logoCornerRadius = 15;

    viewModel.phoneNumFont = SC_FONT_Bold(20);
    viewModel.switchButtonHidden = YES;
   
    viewModel.authButtonTitle = [[NSAttributedString alloc] initWithString:@"一键登录"
                                                                attributes:@{NSForegroundColorAttributeName : UIColor.blackColor,
                                                                             NSFontAttributeName : [UIFont systemFontOfSize:15]
                                                                             }];
    viewModel.authButtonCornerRadius = 23;
    
    viewModel.authButtonImages = @[[UIImage imageWithColor:SC_HEX(0xFFE000)],[UIImage imageWithColor:SC_HEX(0xFFE000)],[UIImage imageWithColor:SC_HEX(0xFFE000)]];
    viewModel.clickAuthButtonBlock = ^(void) {
        NSLog(@"clickAuthButtonBlock");
    };
   
    viewModel.sloganTextColor = UIColor.blackColor;
    viewModel.sloganTextFont = [UIFont systemFontOfSize:14];

    viewModel.checkedImage = [UIImage imageNamed:@"agent_check"];
    viewModel.uncheckedImage = [UIImage imageNamed:@"agent_uncheck"];
    viewModel.defaultCheckBoxState = NO;
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.lineSpacing = 1.33;
    paragraphStyle.alignment = NSTextAlignmentLeft;
    paragraphStyle.paragraphSpacing = 0.0;
    paragraphStyle.lineBreakMode = NSLineBreakByWordWrapping;
    paragraphStyle.firstLineHeadIndent = 0.0;
    viewModel.privacyTermsAttributes = @{
                                         NSForegroundColorAttributeName : UIColor.orangeColor,
                                         NSParagraphStyleAttributeName : paragraphStyle,
                                         NSFontAttributeName : [UIFont systemFontOfSize:12]
                                         };
    OLPrivacyTermItem *item1 = [[OLPrivacyTermItem alloc] initWithTitle:@"《隐私政策》"
                                                                linkURL:[NSURL URLWithString:sc_url_web(kScPrivacyHtml)]
                                                                  index:0];
    OLPrivacyTermItem *item2 = [[OLPrivacyTermItem alloc] initWithTitle:@"《用户协议》"
                                                                linkURL:[NSURL URLWithString:sc_url_web(kScServiceHtml)]
                                                                  index:0];

    viewModel.additionalPrivacyTerms = @[item1, item2];
    viewModel.auxiliaryPrivacyWords = @[@"我已阅读并同意", @"、", @"与", @"，并使用本机号码登录"];
    viewModel.clickCheckboxBlock = ^(BOOL isChecked) {
    };
    
    viewModel.termsAlignment = NSTextAlignmentCenter;
    viewModel.termTextColor = SC_HEX(0x999999);
    viewModel.hasQuotationMarkOnCarrierProtocol = YES;
   
    viewModel.webNaviBgColor = SC_Color_NavWhite;
    viewModel.webNaviHidden = NO;
    
    viewModel.notCheckProtocolHint = @"请选择同意用户协议";
    
    viewModel.autolayoutBlock = ^(UIView *authView, UIView *authContentView, UIView *authBackgroundImageView, UIView *authNavigationView, UIView *authNavigationContainerView, UIView *authBackButton, UIView *authNavigationTitleView, UIView *authLogoView, UIView *authPhoneView, UIView *authSwitchButton, UIView *authLoginButton, UIView *authSloganView, UIView *authAgreementView, UIView *authCheckbox, UIView *authProtocolView, UIView *authClosePopupButton) {
        // content
        [authContentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(authView);
        }];
        
        // background
        [authBackgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(authContentView);
        }];
        
        // navigation
        [authNavigationView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.top.right.equalTo(authContentView);
            make.height.mas_equalTo(64 + (kDevice_Is_iPhoneX ? 24 : 0));
        }];
        
        [authNavigationContainerView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(44);
        }];

        UIView *lineView = [[UIView alloc]init];
        lineView.backgroundColor = SC_HEX(0xB2B2B2);
        [authNavigationContainerView addSubview:lineView];
        [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.mas_equalTo(0);
            make.height.mas_equalTo(0.5);
        }];

        [authBackButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(authNavigationContainerView).offset(10);
            make.centerY.equalTo(authNavigationContainerView);
            make.size.mas_equalTo(CGSizeMake(18, 16));
        }];
    
        [authNavigationTitleView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(authNavigationContainerView);
            make.centerY.equalTo(authNavigationContainerView);
            make.size.mas_equalTo(CGSizeMake(100, 40));
        }];
  
        // logo
        [authLogoView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(authContentView);
            make.top.equalTo(authNavigationView.mas_bottom).offset(80);
            make.size.mas_equalTo(CGSizeMake(90, 90));
        }];
        
        // phone
        [authPhoneView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(authContentView);
            make.top.equalTo(authLogoView.mas_bottom).offset(30);
            make.size.mas_equalTo(CGSizeMake(200, 40));
        }];
        
        // loginbutton
        [authLoginButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(authContentView);
            make.top.equalTo(authNavigationView.mas_bottom).offset(298);
            make.height.mas_equalTo(46);
            make.left.mas_equalTo(15);
            make.right.mas_equalTo(-15);
        }];
        
        // agreementview
        [authAgreementView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(authContentView).offset(20);
            make.right.equalTo(authContentView).offset(-20);
            make.bottom.mas_equalTo(-20);
            make.height.mas_equalTo(80);
        }];
        
        [authCheckbox mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(authAgreementView).offset(4);
            make.top.equalTo(authAgreementView).offset(2);
            make.width.height.mas_equalTo(16);
        }];
        
        [authProtocolView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(authCheckbox.mas_right).offset(5);
            make.right.equalTo(authAgreementView).offset(-4);
            make.height.equalTo(authAgreementView);
            make.top.equalTo(authAgreementView);
        }];
        
        // slogan
        [authSloganView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(authContentView);
            make.bottom.equalTo(authAgreementView.mas_top).offset(-30);
            make.size.mas_equalTo(CGSizeMake(260, 20));
        }];
        
        // 自定义视图
        UIButton *customBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 200, 40)];
        [customBtn setTitle:@"其他方式登录" forState:UIControlStateNormal];
        [customBtn setTitleColor:SC_HEX(0x999999) forState:UIControlStateNormal];
        customBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [customBtn addTarget:self action:@selector(otherLoginClick) forControlEvents:UIControlEventTouchUpInside];
        [authContentView addSubview:customBtn];
        [customBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(authContentView).offset(20);
            make.right.equalTo(authContentView).offset(-20);
            make.height.mas_equalTo(40);
            make.top.equalTo(authLoginButton.mas_bottom).offset(30);
        }];
    };
    
    viewModel.loadingViewBlock = ^(UIView * _Nonnull containerView) {
    };
    
    viewModel.stopLoadingViewBlock = ^(UIView * _Nonnull containerView) {
    };

    viewModel.viewLifeCycleBlock = ^(NSString *viewLifeCycle, BOOL animated) {
        NSLog(@"viewLifeCycle: %@, animated: %@", viewLifeCycle, animated ? @"YES" : @"NO");
        if ([viewLifeCycle isEqualToString:@"viewDidDisappear:"]) {
            [Config sharedConfig].isPresentedWhenSessionExpired = NO;
        } else if ([viewLifeCycle isEqualToString:@"viewDidLoad"]) {
            // 授权页面出现时，关掉进度条
//            [GTProgressHUD hideAllHUD];
        }
    };
    return viewModel;
}

- (void)dismissAuthVC {
    [OneLogin dismissAuthViewController:NO completion:^{
    }];
}

- (void)otherLoginClick{
    SCLoginVC *loginVC = [[SCLoginVC alloc] init];
    loginVC.loginSuccess = self.loginSuccess;
    loginVC.isPresented = self.isPresented;
    loginVC.fromOtherLogin = YES;
    loginVC.viewController = _viewController;
   if (self.isPresented) {
       
     SCNavigationController *loginNav = [[SCNavigationController alloc] initWithRootViewController:loginVC];
       loginNav.modalPresentationStyle = UIModalPresentationFullScreen;
      
       CATransition *animation = [CATransition animation];
       animation.duration = 0.5;
       animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
       animation.type = kCATransitionPush;
       animation.subtype = kCATransitionFromRight;
       
       [[OneLogin currentAuthViewController].view.window.layer addAnimation:animation forKey:nil];
       [[OneLogin currentAuthViewController] presentViewController:loginNav animated:NO completion:nil];
        
    }else{
        [self.viewController.navigationController pushViewController:loginVC animated:YES];
    }
}

- (void)finishRequestingToken:(NSDictionary *)result {
    if (result.count > 0 && result[OLStatusKey] && 200 == [result[OLStatusKey] integerValue]) {
        NSString *token = result[OLTokenKey];
        NSString *appID = result[OLAppIDKey];
        NSString *processID = result[OLProcessIDKey];
        NSString *authcode = result[OLAuthcodeKey];
        [self validateToken:token appID:appID processID:processID authcode:authcode];
    } else {
        if (result[OLErrCodeKey] && [result[OLErrCodeKey] isEqual:OLErrorCode_20302]) { // 点击授权页面返回按钮退出授权页面
            [OneLogin dismissAuthViewController:NO completion:^{
            }];
        } else if (result[OLErrCodeKey] && [result[OLErrCodeKey] isEqual:OLErrorCode_20303]) { // 点击授权页面切换账号按钮
            [MBProgressHUD showError:@"切换账号" toView:nil];
            [OneLogin dismissAuthViewController:NO completion:^{
            }];
        } else {
            [MBProgressHUD showError:@"登录失败" toView:nil];
            [OneLogin dismissAuthViewController:NO completion:^{
            }];
        }
    }
}

// 使用token获取用户的登录信息
- (void)validateToken:(NSString *)token appID:(NSString *)appID processID:(NSString *)processID authcode:(NSString *)authcode {
  
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
 
    NSMutableDictionary *geetest = [[NSMutableDictionary alloc]init];
    [geetest setObject:processID forKey:@"process_id"];
    [geetest setObject:authcode forKey:@"authcode"];
    [geetest setObject:token forKey:@"token"];
    
    [params setObject:geetest forKey:@"geetest"];
  
    [params setObject:@"1" forKey:kAuthorCode];
    [params setObject:@"15" forKey:kSource];
    NSDictionary *dic = [NSBundle mainBundle].infoDictionary;
    [params setObject:dic[@"CFBundleShortVersionString"] forKey:kVersion];
    [params setObject:@(4) forKey:@"loginType"];
    [params setObject:@"2" forKey:@"password"];
  
    MBProgressHUD *hud = [MBProgressHUD showMessage:@"正在登录..." toView:nil];
    WEAKSELF
    [[SCHttpManager shareInstance] httpPost:@"/userprod/user/login" param:params completion:^(id response, NSError *error){
      STRONGSELF
      if(!strongSelf){
          Return_From_Block
      }
      [hud hide:YES];
      if (error) {
        [MBProgressHUD showError:error.localizedDescription toView:nil];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [OneLogin dismissAuthViewController:NO completion:^{
            self->otherLogin_();
            
          }];
        });
      } else {
        
        NSDictionary *data = response;
        NSNumber *sessionId = data[kSessionId];
        [[SCHttpManager shareInstance] updateHeaderFieldSession:sessionId];
        [[NSUserDefaults standardUserDefaults] setObject:sessionId forKey:kSessionId];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kIsLogin];
        [[NSUserDefaults standardUserDefaults] setObject:data[@"username"] forKey:kUsername];
        [[NSUserDefaults standardUserDefaults] setObject:data[kUserId] forKey:kUserId];
        [[NSUserDefaults standardUserDefaults] setObject:data[kMerchantId] forKey:kMerchantId];
        
        User *user = [User MR_findFirstOrCreateByAttribute:kUserId withValue:[[NSUserDefaults standardUserDefaults] objectForKey:kUserId]];
        user.phone = [NSString SC_trimString:data[@"username"]];
        user.username = [NSString SC_trimString:data[@"username"]];
        user.face  = data[kFace];
        user.fullname = data[kFullname];
        user.roleName = data[kRoleName];
        user.perms = [data[kPerms] integerValue];
        user.merchantName = data[kMerchantName];
        user.merchantAbbreviation = data[kMerchantAbbreviation];
        user.merchantId = [data[kMerchantId] intValue];
        user.merchantLogoPic = data[kMerchantLogoPic];
        user.imToken = data[kIMToken];
        user.imUserId = data[kIMUserId];
        user.imTokenExpireTimeSeconds = [data[kIMTokenExpireTimeSeconds] intValue];
        user.isFranchisee = data[kIsFranchisee] ? [data[kIsFranchisee] intValue]:0;
        
        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
        [Config fetchMaintenEnable];

        [JPUSHService setAlias:[NSString stringWithFormat:@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:kUserId]] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            NSLog(@">>>setAlias:%zd,iAlias:%@",iResCode, iAlias);
        } seq:10];
      
        [self dismissAuthAndOtherLogin];
        
//        [[NSNotificationCenter defaultCenter] postNotificationName:SCNOTIFICATION_LOGIN_IN_OUT object:nil];
    }
    }];
}

- (void)dismissAuthAndOtherLogin{
    [OneLogin dismissAuthViewController:NO completion:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            self.loginSuccess();
        });
    }];
}

@end
